package com.sddfp.system.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sddfp.common.constant.user.UserConstant;
import com.sddfp.common.exception.Assert;
import com.sddfp.common.pojo.UserRegisterDto;
import com.sddfp.common.result.enums.impl.BusinessCode;
import com.sddfp.system.entity.User;
import com.sddfp.system.entity.UserDetail;
import com.sddfp.system.mapper.UserDetailMapper;
import com.sddfp.system.mapper.UserMapper;
import com.sddfp.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yellow doctor
 * @since 2025-06-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;


    @Autowired
    UserDetailMapper userDetailMapper;

    @Transactional
    @Override
    public void register(UserRegisterDto userRegisterDto) {

        //查看电话是否重复
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getPhone, userRegisterDto.getPhone());
        User user = userMapper.selectOne(wrapper);
        Assert.error(user!=null, BusinessCode.USER_EXISTED);

        User user1 = new User();
        user1.setPhone(userRegisterDto.getPhone());
        user1.setUserName(userRegisterDto.getUserName());
        String hashpw = BCrypt.hashpw(userRegisterDto.getPwd());
        user1.setPwd(hashpw);
        user1.setUserType(UserConstant.USER_TYPE_PERSONAL);
        user1.setUserStatus(false);
        userMapper.insert(user1);

        UserDetail userDetail = new UserDetail();
        userDetail.setUserName(userRegisterDto.getUserName());
        userDetail.setPhone(userRegisterDto.getPhone());
        userDetail.setBorrowMoney(BigDecimal.valueOf(0.0));
        userDetail.setId(user1.getId());
        userDetail.setUserCode("UC_"+UUID.randomUUID().toString().substring(0, 8));
        userDetail.setCardBindStatus(false);
        userDetailMapper.insert(userDetail);
    }

    @Override
    public void login(UserRegisterDto userRegisterDto) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone, userRegisterDto.getPhone());
        User user = userMapper.selectOne(wrapper);
        Assert.error(user==null, BusinessCode.USER_NOT_EXIST);

        boolean b = BCrypt.checkpw(userRegisterDto.getPwd(), user.getPwd());
        Assert.error(!b,BusinessCode.LOGIN_FAIL);

    }
}
